﻿using System;
using System.Collections.Generic;
using OestsCommon.Model;
using OestsDataBase;
using OestsServer.Handlers;
using LNet;
using OestsServer.Net;
using System.Net;
using System.Net.Sockets;
using OestsServer.Handlers.UnityHandlers;
using System.Threading;
using System.Timers;
using System.Linq;

#if vv
namespace OestsServer.Managers.ClientManagers
{

    /*
    /// <summary>
    /// 客户端用户管理器
    /// </summary>
    public class UnityClientManager //: ClientManager
    {
        public string HandlerNamspace => "OestsServer.Handlers.UnityHandlers";
        public int ConnectCount { get { return clientList.Count; } }

        /// <summary>
        /// /连接到服务器，没有用户登录的 客户端集合
        /// </summary>
        private static List<UnityClientChannel> clientList = new List<UnityClientChannel>();


        public UnityClientManager()
        {
            Thread thread = new Thread(ConnectState)
            {
                IsBackground = true
            };
            thread.Start();
        }
        private System.Timers.Timer timer;

        private void ConnectState()
        {
            //10秒检测一次客户端是否连接
            timer = new System.Timers.Timer(10000);
            timer.Elapsed += new ElapsedEventHandler(HeartBeatHandler);//到达时间执行事件
            timer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            timer.Start();
        }

        private void HeartBeatHandler(object sender, ElapsedEventArgs e)
        {
            long nowTime = DateTime.Now.Ticks;

            foreach (var client in clientList)
            {
                if (nowTime - client.lastPing > 200000000)
                {
                    client.DisConnectedHandler();
                }
            }
        }

        //添加一个客户端
        public void AddClient(string listenerName, Socket socket)
        {
            UnityClientChannel client = new UnityClientChannel(listenerName, socket, this);
            lock (clientList)
            {
                clientList.Add(client);
            }
        }



        public static void DeleteClient(UnityClientChannel client)
        {
            lock (clientList)
            {
                for (int i = 0; i < clientList.Count; i++)
                {
                    if (clientList[i] == client)
                    {
                        //  clientList[i].Close();
                        clientList[i] = null;
                        clientList.RemoveAt(i);
                        break;
                    }
                }

            }
        }

        /// <summary>
        /// 连接断开处理
        /// </summary>
        /// <param name="client"></param>
        public void DisConnectedHandler(ClientChannel client)
        {
            UnityClientChannel mc = client as UnityClientChannel;

            //得到客户端用户对象后，移除客户端
            User u = client.User;
            //移除客户端
            if (clientList.Contains(mc))
            {
                DeleteClient(mc); //移除client client 为null了
            }
            /****************************  处理用户 逻辑 **********************************/
    ProjectType type = mc.ProjectType;
            if (u == null) return;//用户为空，直接退出
#region 学员逻辑 （学员在房间内，处理终止实训逻辑）

            if (client.Student != null)
            {
                // Student s = client.User as Student;
                if (client.Student._room != null)
                {
                    if (client.Student._room.RoomId > 0)
                    {
                        TrainHandler.AbortTrain(type, client.Student._room.RoomId, client.User.DBid);  //处理终止实训逻辑
                    }
                }
            }
#endregion
        }

        /// <summary>
        /// 检查一个用户是否在线
        /// </summary>
        /// <param name="cType"></param>
        /// <param name="uType"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool CheckUserIsExist(ProjectType cType, /*UserType uType,*/ int userDbId)
        {
            lock (clientList)
            {
                foreach (var client in clientList)
                {
                    if (client != null)
                    {
                        if (client.ProjectType == cType)
                        {
                            if (client.User == null)
                            {
                                continue;
                            }
                            if (/*client.User.Type == uType &&*/ client.User.DBid == userDbId)
                                return true;
                        }
                    }

                }
            }
            return false;
        }
      

        public static Student GetStudentById(int stuId)
        {
            foreach (var clientChannel in clientList)
            {
                if (clientChannel.Student == null) continue;

                if (clientChannel.Student.DBid == stuId)
                {
                    return clientChannel.Student;
                }

            }
            return null;
        }

        public static UnityClientChannel GetClient(UserType userType, int userId)
        {
            lock (clientList)
            {
                for (int i = clientList.Count - 1; i > -1; i--)
                {
                    if (clientList[i].User != null)
                    {
                        if (clientList[i].User.Type == userType && clientList[i].User.DBid == userId)
                        {
                            return clientList[i];
                        }
                    }
                }
            }
            return null;
        }

        public void LogoffAccount(int userId)
        {
            throw new NotImplementedException();
        }

        public List<User> GetOnlineUsers()
        {
            lock (clientList)
            {
                var clientUsers = clientList.Where(x => x.User != null);
                if (clientUsers != null)
                    return clientUsers.Select(x => x.User).ToList();
                return null;
            }
        }
    }*/
}
#endif